package com.maiji.cloud.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.maiji.cloud.entities.shopingmall.DiscountCoupon;
import com.maiji.cloud.entities.shopingmall.DiscountCouponLog;
import com.maiji.cloud.mapper.DiscountCouponMapper;
import com.maiji.cloud.request.ReqMetaData;
import com.maiji.cloud.response.BaseMetaResDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.ResMetaData;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.service.DiscountCouponService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.maiji.cloud.utils.UUID_MD5;
import org.apache.commons.lang.BooleanUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DiscountCouponServiceImpl extends ServiceImpl<DiscountCouponMapper, DiscountCoupon> implements DiscountCouponService {

    @Value("${realmName}")
    private String realmName;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public BaseMetaResDto<List<DiscountCoupon>> findAllDiscountCoupons(Integer type, Boolean amount, ReqMetaData metaData) {
        EntityWrapper<DiscountCoupon> entityWrapper = new EntityWrapper<>();
        if (type != null) entityWrapper.eq("type", type);
        if (BooleanUtils.isTrue(amount)) entityWrapper.gt("amount", 0);
        if (BooleanUtils.isFalse(amount)) entityWrapper.eq("amount", 0);
        entityWrapper.orderAsc(Arrays.asList("type", "face_value"));
        Page<DiscountCoupon> page = selectPage(new Page<>(metaData.getPage(), metaData.getSize()), entityWrapper);
        List<DiscountCoupon> discountCoupons = page.getRecords().parallelStream().map(dc -> dc.setRealmName(realmName)).collect(Collectors.toList());
        ResMetaData resMetaData = new ResMetaData(page.getCurrent(), page.getSize(), page.getTotal());
        return new BaseMetaResDto<List<DiscountCoupon>>(Status.SUCCESS).setData(discountCoupons).setResMetaData(resMetaData);
    }

    @Override
    public BaseResDto editDiscountCoupon (DiscountCouponLog discountCouponLog) {
        discountCouponLog.setEditDate(new Date());
        DiscountCoupon discountCoupon = new DiscountCoupon();
        BeanUtils.copyProperties(discountCouponLog, discountCoupon);
        if ("删除规则".equals(discountCouponLog.getOperationDesc())) {
            if (! updateById(discountCoupon))return new BaseResDto(Status.ERROR);
            mongoTemplate.save(discountCouponLog.setOperationDesc("删除规则"), DiscountCouponLog.TABLE_NAME);
            return new BaseResDto(Status.SUCCESS);
        }
        if (StringUtil.isBlank(discountCoupon.getUuId())) {
            if (! insert(discountCoupon.setUuId(UUID_MD5.getUUID()))) return new BaseResDto(Status.ERROR);
            mongoTemplate.save(discountCouponLog.setOperationDesc("添加规则"), DiscountCouponLog.TABLE_NAME);
        } else {
            if (! updateById(discountCoupon)) return new BaseResDto(Status.ERROR);
            mongoTemplate.save(discountCouponLog.setOperationDesc("修改规则"), DiscountCouponLog.TABLE_NAME);
        }
        return new BaseResDto(Status.SUCCESS);
    }

    @Override
    public BaseMetaResDto<List<DiscountCouponLog>> findAllDiscountCouponLogs (Integer type,
                                                    String operationDesc, List<Date> updateDates, ReqMetaData metaData) {
        Query query = new Query(Criteria.where("type").is(type));
        if (StringUtil.isNotBlank(operationDesc)) query.addCriteria(Criteria.where("operationDesc").is(operationDesc));
        query.with(new Sort(new Sort.Order(Sort.Direction.DESC,"editDate")));
        if (updateDates != null) {
            Date startDate = updateDates.size() > 0 ? updateDates.get(0): null;
            Criteria updateDateCriteria = Criteria.where("editDate");
            Boolean updFlag = false;
            if (startDate != null) {
                updateDateCriteria = updateDateCriteria.gte(startDate);
                updFlag = true;
            }
            Date endDate = updateDates.size() > 1 ? updateDates.get(1): null;
            if (endDate != null) {
                updateDateCriteria = updateDateCriteria.lte(endDate);
                updFlag = true;
            }
            if (updFlag) query.addCriteria(updateDateCriteria);
        }
        Long total = mongoTemplate.count(query, DiscountCouponLog.TABLE_NAME);
        query.skip((metaData.getPage() - 1) * metaData.getSize()).limit(metaData.getSize());
        List<DiscountCouponLog> discountCouponLogs = mongoTemplate.find(query, DiscountCouponLog.class, DiscountCouponLog.TABLE_NAME);
        ResMetaData resMetaData = new ResMetaData(metaData.getPage(), metaData.getSize(), total);
        return new BaseMetaResDto<List<DiscountCouponLog>>(Status.SUCCESS).setData(discountCouponLogs).setResMetaData(resMetaData);
    }

}
